package com.example.pad_sys;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;


import com.example.pad_sys.databinding.ItemInputLayoutBinding;

import java.util.Objects;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

public class ItemInputLayout extends LinearLayout {

    public static final int MODE_TEXT = 0;
    public static final int MODE_EDIT = 1;
    public static final int MODE_SPINNER = 2;
    private final ItemInputLayoutBinding binding;

    private int index;

    public ItemInputLayout(Context context) {
        this(context, null);
    }

    public ItemInputLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ItemInputLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        binding = DataBindingUtil.inflate(inflater, R.layout.item_input_layout, this, false);
        addView(binding.getRoot());
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public int getIndex() {
        return index;
    }

    public ItemInputLayoutBinding getBinding() {
        return binding;
    }

    public String getItemValue() {
        return Objects.requireNonNull(binding.evValue.getText()).toString();
    }

    @SuppressLint("ClickableViewAccessibility")
    public void setItemMode(ItemLayoutListener l, int mode) {
        itemLayoutListener = l;
        switch (mode) {
            case MODE_SPINNER:
            case MODE_EDIT:
                binding.evValue.setEnabled(true);
                binding.evValue.setFocusable(true);
                binding.evValue.setFocusableInTouchMode(true);
                binding.evValue.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            if (itemLayoutListener != null) {
                                itemLayoutListener.onItemEditClick(ItemInputLayout.this, v);
                            }
                        }
                        return false;
                    }
                });
                break;
            default:
                binding.evValue.setEnabled(false);
                break;
        }
    }

    private ItemLayoutListener itemLayoutListener;

    public interface ItemLayoutListener {
        void onItemEditClick(ItemInputLayout layout, Object... objects);
    }

}
